//@version=6
indicator("Adaptive Trend Filter", shorttitle="IAFL", overlay=true, max_labels_count=500, max_bars_back=500)


// ───── Strategy Presets ─────
preset = input.string("Intraday", "Strategy Preset", options=["Positional", "Swing", "Intraday"])

// ───── Indicator Toggles ─────
useSupertrend = input.bool(true, "Use Supertrend")
useADX        = input.bool(true, "Use ADX")

// ───── Signal Display Mode ─────
signalMode = input.string("Show All Signals", "Signal Display Mode", options=["Show All Signals", "Show Buy Signals", "Show Sell Signals"])
showBuy = signalMode == "Show All Signals" or signalMode == "Show Buy Signals"
showSell = signalMode == "Show All Signals" or signalMode == "Show Sell Signals"


// ───── Trade Info Box Settings ─────
showInfoBox = input.bool(true, "Show Trade Info Box")
boxPosition = input.string("Top Right", "Box Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right"])

// ───── Risk Management Inputs ─────
useAutoSLTP     = input.bool(true, "Use Auto SL/TP (based on indicators)?")
sl_percent      = input.float(0.5, "Manual Stop Loss %")
tp_percent      = input.float(1.0, "Manual Take Profit %")
riskRewardRatio = input.float(2.0, "Auto SL/TP: Risk-Reward Ratio")

// ───── Internal Parameters (Defaults Changed) ─────
atrPeriod       = input.int(19, "ATR Length", minval=1)
factor          = input.float(2.4, "Supertrend Factor", minval=0.1, step=0.1)

adxLength    = 12
adxThreshold = 20

// ───── Preset Overrides ─────
if preset == "Positional"
    factor := 11
    adxThreshold := 25
    adxLength := 25
else if preset == "Swing"
    trPeriod       = input.int(11, "ATR Length", minval=1)
    factor := 11

adxThreshold := 21

// ───── Supertrend ─────
[supertrend, dir] = ta.supertrend(factor, atrPeriod)
trendUp   = dir < 0
trendDown = dir > 0

// ───── ADX (manual) ─────
upMove   = high - high[1]
downMove = low[1] - low
plusDM   = (na(upMove)  or (upMove  > downMove and upMove  > 0)) ? upMove  : 0
minusDM  = (na(downMove) or (downMove > upMove  and downMove > 0)) ? downMove : 0
trur = math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
tr       = ta.rma(trur, adxLength)
plusDI   = 100 * ta.rma(plusDM,  adxLength) / tr
minusDI  = 100 * ta.rma(minusDM, adxLength) / tr
dx       = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
adx      = ta.rma(dx, adxLength)
adxOK    = adx > adxThreshold

// ───── Buy / Sell Logic ─────
supertrendCrossUp   = ta.crossover(close, supertrend)
supertrendCrossDown = ta.crossunder(close, supertrend)

buySignal = (not useSupertrend or (supertrendCrossUp and trendUp)) and (not useADX or adxOK)
sellSignal = (not useSupertrend or (supertrendCrossDown and trendDown)) and (not useADX or adxOK)

// ───── Labels for Price Signals ─────
if showBuy and buySignal
    label.new(x=bar_index, y=low, text="Buy @ " + str.tostring(close, "#.##"),
              style=label.style_label_up, color=color.green, textcolor=color.white, size=size.small)

if showSell and sellSignal
    label.new(x=bar_index, y=high, text="Sell @ " + str.tostring(close, "#.##"),
              style=label.style_label_down, color=color.red, textcolor=color.white, size=size.small)

// ───── Trade Info Tracking ─────
var string lastSignal = "None"
var float entryPrice = na
var float stopLoss = na
var float takeProfit = na
var bool tradeOpen = false
atr = ta.atr(atrPeriod)

if buySignal
    lastSignal := "Buy"
    entryPrice := close
    stopLoss := useAutoSLTP ? supertrend : close * (1 - sl_percent / 100)
    takeProfit := useAutoSLTP ? (entryPrice + riskRewardRatio * (entryPrice - stopLoss)) : close * (1 + tp_percent / 100)
    tradeOpen := true

if sellSignal
    lastSignal := "Sell"
    entryPrice := close
    stopLoss := useAutoSLTP ? supertrend : close * (1 + sl_percent / 100)
    takeProfit := useAutoSLTP ? (entryPrice - riskRewardRatio * (stopLoss - entryPrice)) : close * (1 - tp_percent / 100)
    tradeOpen := true

// Always exit on opposite signal (no toggle)
tradeOpen := not ((lastSignal == "Buy" and sellSignal) or (lastSignal == "Sell" and buySignal))

profitLoss = not na(entryPrice) ? (lastSignal == "Buy" ? (close - entryPrice) : (entryPrice - close)) : na
statusText = tradeOpen ? "Open" : (lastSignal == "None" ? "Waiting" : "Closed")

// ───── Info Box ─────
pos = boxPosition == "Top Right" ? position.top_right :
       boxPosition == "Top Left" ? position.top_left :
       boxPosition == "Bottom Left" ? position.bottom_left :
       position.bottom_right

var table statsTbl = table.new(pos, 5, 2, frame_width=1, frame_color=color.white, border_color=color.white, bgcolor=color.new(color.black, 50))

f_show(val, fmt) => na(val) ? "-" : str.tostring(val, fmt)
txtPL = "-"
colPL = color.white

if showInfoBox and barstate.islast
    if not na(profitLoss)
        txtPL := str.tostring(profitLoss, "#.##")
        colPL := profitLoss >= 0 ? color.lime : color.red

    table.cell(statsTbl, 0, 0, "Signal", text_color=color.white, bgcolor=color.new(color.gray, 80), text_size=size.small)
    table.cell(statsTbl, 0, 1, lastSignal, text_color=color.white, bgcolor=color.new(color.gray, 80), text_size=size.small)

    table.cell(statsTbl, 1, 0, "SL", text_color=color.white, bgcolor=color.rgb(200, 50, 50), text_size=size.small)
    table.cell(statsTbl, 1, 1, f_show(stopLoss, "#.##"), text_color=color.white, bgcolor=color.rgb(200, 50, 50), text_size=size.small)

    table.cell(statsTbl, 2, 0, "TGT", text_color=color.white, bgcolor=color.rgb(0, 120, 0), text_size=size.small)
    table.cell(statsTbl, 2, 1, f_show(takeProfit, "#.##"), text_color=color.white, bgcolor=color.rgb(0, 120, 0), text_size=size.small)

    table.cell(statsTbl, 3, 0, "P/L", text_color=color.white, bgcolor=color.rgb(0, 0, 150), text_size=size.small)
    table.cell(statsTbl, 3, 1, txtPL, text_color=colPL, bgcolor=color.rgb(0, 0, 150), text_size=size.small)

    table.cell(statsTbl, 4, 0, "Status", text_color=color.white, bgcolor=color.gray, text_size=size.small)
    table.cell(statsTbl, 4, 1, statusText, text_color=color.white, bgcolor=color.gray, text_size=size.small)
